package server;

import java.io.*;

/**
 * description MyClassLoader
 * author wy
 * date 2021-06-27 15:26
 **/
public class MyClassLoader extends ClassLoader
{
    public Class<?> loadClass(String basePath, String className)
    {
        byte[] bytes = getClassBytes(basePath, className);
        return this.defineClass(className, bytes, 0, bytes.length);
    }

    private byte[] getClassBytes(String basePath, String className)
    {
        InputStream in = null;
        ByteArrayOutputStream out = null;
        String path = basePath + File.separatorChar +
                className.replace('.', File.separatorChar) + ".class";
        try
        {
            in = new FileInputStream(path);
            out = new ByteArrayOutputStream();

            byte[] buffer = new byte[2048];
            int len = 0;
            if ((len = in.read(buffer)) != -1)
            {
                out.write(buffer, 0, len);
            }
            return out.toByteArray();
        }
        catch (FileNotFoundException e)
        {
            e.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return null;
    }
}
